#ifndef _PROCESSWRAPPER
#define _PROCESSWRAPPER

//#define _USE_WIN32_PROC

#define SF_ALLOC 0x1
#define SF_SHOW_WINDOW 0x2
#define SF_WAIT_IDLE 0x4
#define SF_REDIRECT_STDIN 0x1000
#define SF_REDIRECT_STDOUT 0x2000
#define SF_REDIRECT_STDERR 0x4000
#define SF_REDIRECT_OUTPUT (0x8000 | SF_REDIRECT_STDOUT)

class CProcessWrapper
{
public:
	CProcessWrapper(int flags = 0);
	~CProcessWrapper()
	{
		Cleanup();
	}
	bool Spawn(char* commandLine, char* curDir = 0, char** env = 0);
	int WaitIdle(int milliseconds);
	static int Run(char* commandLine, char* curDir = 0);
	int ReadStdout();
	int ReadStderr();
	int Read(void* buffer, int bufsize);
	int Write(void* data, int len);
	int Wait(int timeout = 0);
	bool Terminate();
	bool Suspend(bool resume);
	bool SetPriority(int priority);
	bool SetAffinity(int mask);
	void AddEnvVariable(char* envName, char* envValue);
	void PurgeVariable();
	void AllocateBuffer(int bytes);
	void FreeBuffer();
	void CloseStdout();
	void CloseStdin();
	void CloseStderr();
	bool IsProcessRunning(int* pexitcode = 0);
	static int GetProcessIdByHandle(HANDLE hProcess);
	static bool MakePipe(int& readpipe, int& writepipe, int bufsize = 16384, bool inheritRead = false, bool inheritWrite = false, int flags = -1);
	static char** Tokenize(char* str, char delimiter = ' ');
	void Cleanup();
	int flags;
	char *conbuf;
	int conbufsize;
#ifdef _USE_WIN32_PROC
	HANDLE hStdinWrite;
	HANDLE hStdoutRead;
	HANDLE hStderrRead;
#else
	int fdStdinWrite;
	int fdStdoutRead;
	int fdStderrRead;
#endif
	HANDLE hProcess;
private:
#ifdef _USE_WIN32_PROC
	int ReadOutput(HANDLE handle);
#else
	int ReadOutput(int fd);
#endif
	char *pchCommandLine;
	char *pchPath;
	int pid;
	int envsize;
};

#endif